import { useEffect, useState } from 'react';
import debounce from '@/utils/debounce';

function usePagination(props?: any) {
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: props?.pageSize || 10,
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0,
    showTotal: (total: number) => `总共${total}条数据`,
  });

  // 表格页码 改变
  const onChange = (page: any) => {
    if (pagination.pageSize !== page.pageSize) {
      pagination.current = 1;
    } else {
      pagination.current = page.current;
    }
    pagination.pageSize = page.pageSize;
    pagination.total = page.total;
    setPagination({ ...pagination });
  };

  return { pagination, setPagination, onChange };
}

export function useHeight(min = 100) {
  const [height, setHeight] = useState(0);

  const computedHeight = () => {
    const totalHeight = document.documentElement.clientHeight;
    const res = totalHeight - min;
    setHeight(res);
  };
  const reset = debounce(computedHeight, 100, false);

  useEffect(() => {
    computedHeight();
    window.addEventListener('resize', reset);
    return () => {
      window.removeEventListener('resize', computedHeight);
    };
  }, []);

  return {
    height,
  };
}

export default usePagination;
